package com.zz.nondatain.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.zz.nondatain.model.BaiduTokenResponse;
import com.zz.nondatain.network.RetrofitClient;

import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * 百度人脸识别Token管理器
 * 用于获取、存储和管理百度AI平台的access_token
 */
public class FaceTokenManager {
    private static final String TAG = "FaceTokenManager";
    private static final String PREF_NAME = "baidu_face_prefs";
    private static final String KEY_ACCESS_TOKEN = "access_token";
    private static final String KEY_REFRESH_TOKEN = "refresh_token";
    private static final String KEY_EXPIRY_TIME = "expiry_time";
    
    // 百度AI平台的API Key和Secret
    // 注意：需要替换为从百度AI平台获取的正确值
    private static final String CLIENT_ID = "vbYXt2v6ivNYLwoONTQHzMps";
    private static final String CLIENT_SECRET = "rtxC8D4ZhcatfxP3ukf872ZVJJj0oKfn";
    private static final String GRANT_TYPE = "client_credentials";
    
    // 单例实例
    private static FaceTokenManager instance;
    
    private SharedPreferences prefs;
    private Context context;
    private CompositeDisposable disposables = new CompositeDisposable();
    
    // 私有构造函数
    private FaceTokenManager(Context context) {
        this.context = context.getApplicationContext();
        this.prefs = this.context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }
    
    /**
     * 获取FaceTokenManager单例
     */
    public static synchronized FaceTokenManager getInstance(Context context) {
        if (instance == null) {
            instance = new FaceTokenManager(context);
        }
        return instance;
    }
    
    /**
     * 获取当前存储的token
     * @return token或null（如果不存在或已过期）
     */
    public String getToken() {
        String token = prefs.getString(KEY_ACCESS_TOKEN, null);
        long expiryTime = prefs.getLong(KEY_EXPIRY_TIME, 0);
        
        // 检查token是否存在及是否过期
        if (token == null || System.currentTimeMillis() > expiryTime) {
            return null;
        }
        
        return token;
    }
    
    /**
     * 检查token是否有效（存在且未过期）
     */
    public boolean isTokenValid() {
        return getToken() != null;
    }
    
    /**
     * 从百度AI平台获取新的token
     * @param callback 回调，返回token获取结果
     */
    public void refreshToken(final TokenCallback callback) {
        // 使用专门的百度AI平台RetrofitClient实例
        RetrofitClient baiduClient = RetrofitClient.getBaiduInstance();
        
        Log.d(TAG, "开始请求百度token...");
        Log.d(TAG, "请求URL: https://aip.baidubce.com/oauth/2.0/token");
        Log.d(TAG, "参数: grant_type=" + GRANT_TYPE + "&client_id=" + CLIENT_ID);
        
        disposables.add(
            baiduClient.getApiService().getBaiduToken(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    response -> {
                        Log.d(TAG, "百度API响应: " + response);
                        if (response.hasError()) {
                            Log.e(TAG, "Token获取失败: " + response.getErrorDescription());
                            if (callback != null) {
                                callback.onFailure("获取Token失败: " + response.getErrorDescription());
                            }
                        } else {
                            // 计算过期时间（提前10分钟过期，确保安全）
                            long expiryTimeMillis = System.currentTimeMillis() + 
                                    TimeUnit.SECONDS.toMillis(response.getExpiresIn() - 600);
                            
                            // 保存token
                            saveToken(response.getAccessToken(), response.getRefreshToken(), expiryTimeMillis);
                            
                            Log.d(TAG, "Token获取成功: " + response.getAccessToken());
                            Log.d(TAG, "Token过期时间: " + expiryTimeMillis);
                            
                            if (callback != null) {
                                callback.onSuccess(response.getAccessToken());
                            }
                        }
                    },
                    throwable -> {
                        Log.e(TAG, "Token获取异常", throwable);
                        // 增加更详细的错误信息记录
                        if (throwable instanceof retrofit2.adapter.rxjava3.HttpException) {
                            retrofit2.adapter.rxjava3.HttpException httpException = 
                                (retrofit2.adapter.rxjava3.HttpException) throwable;
                            int code = httpException.code();
                            String message = httpException.message();
                            Log.e(TAG, "HTTP错误: " + code + " " + message);
                            
                            if (code == 401) {
                                Log.e(TAG, "认证失败，请检查您的API Key和Secret Key是否正确");
                            }
                        }
                        
                        if (callback != null) {
                            callback.onFailure("获取Token异常: " + throwable.getMessage());
                        }
                    }
                )
        );
    }
    
    /**
     * 获取有效的token，如果当前token无效则自动刷新
     * @param callback 回调，返回token
     */
    public void getValidToken(final TokenCallback callback) {
        String token = getToken();
        if (token != null) {
            if (callback != null) {
                callback.onSuccess(token);
            }
        } else {
            refreshToken(callback);
        }
    }
    
    /**
     * 保存token信息到SharedPreferences
     */
    private void saveToken(String accessToken, String refreshToken, long expiryTime) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(KEY_ACCESS_TOKEN, accessToken);
        editor.putString(KEY_REFRESH_TOKEN, refreshToken);
        editor.putLong(KEY_EXPIRY_TIME, expiryTime);
        editor.apply();
    }
    
    /**
     * 清除保存的token信息
     */
    public void clearToken() {
        SharedPreferences.Editor editor = prefs.edit();
        editor.remove(KEY_ACCESS_TOKEN);
        editor.remove(KEY_REFRESH_TOKEN);
        editor.remove(KEY_EXPIRY_TIME);
        editor.apply();
    }
    
    /**
     * 释放资源
     */
    public void dispose() {
        if (disposables != null && !disposables.isDisposed()) {
            disposables.dispose();
        }
    }
    
    /**
     * Token获取回调接口
     */
    public interface TokenCallback {
        void onSuccess(String token);
        void onFailure(String error);
    }
} 